import process from 'child_process';
import compiler from 'vue-template-compiler';
import fs from 'fs';
import path from 'path';
import {parse} from '@babel/parser';
import traverse from '@babel/traverse';
import generate from '@babel/generator';
import t from '@babel/types';

const mustHand = {
  methods_initData: '未处理 methods.initData',
  // orderItems_sortProp: 'orderItems 中有字段可能不在生效的sortProp中',
  tableVIf: 'JNPF-table 有v-if绑定，请把此绑定值放到created获取表格异步字段的await语法之后改为true',
  jnpfTableQuery: 'JNPF-tableQuery 组件未自动设置',
  systemSearchView: 'systemSearchView 组件未自动设置',
  showSortDrawer: '没有数据排序设置入口',
}

const global = new Proxy({}, {
  get(target, key){
    // console.log(`get global.${key} = ${target[key]}`)
    return target[key];
  },
  set(target, key, value) {
    console.log(`⚙️ set global.${key} = ${value}`)
    return target[key] = value;
  }
})

let echoIndex = 0
function echoLog(str) {
  console.log(`${++echoIndex}、${str} ✅_`);
}

// 判断是否需要删除的superQueryJson项
function shouldRemoveItem(item) {
  if (!item.type) return false;
  if (['input', 'custom'].includes(item.type)) return true;

  const removeKeywords = ['单据状态', '审批状态', '日期', '时间', '是否'];
  return removeKeywords.some(keyword => item.label && item.label.includes(keyword));
}

// 在ast中查找指定属性的首个path
function findFirstTargetPathFromAst(ast, key) {
  let result = null;
  // 遍历AST寻找data函数中的orderItems属性
  traverse.default(ast, {
    ObjectProperty(path) {
      if (!result && path.node.key.name === key) {
        result = path
      }
    },
  });
  return result;
}


/**
 * 将代码字符串作为 AST 处理，并返回处理后的代码字符串。
 * @param {string} code - 要处理的 JavaScript/JSX 代码字符串。
 * @param {function} cb - 回调函数，接收 (ast, { parser, traverse, types, generate }) 作为参数。
 *                        在此函数中可以修改传入的 ast。
 * @param {Object} options - 可选的解析和生成选项。
 * @param {Object} options.parseOptions - 传递给 @babel/parser 的选项。
 * @param {Object} options.generateOptions - 传递给 @babel/generator 的选项。
 * @returns {string} - 处理后的代码字符串。
 */
function codeAsAstHandler(code, cb) {
  // 包装 code 使其成为有效的对象字面量表达式
  const wrappedCode = `({ ${code.trim()} })`;

  const ast = parse(wrappedCode, {
    sourceType: 'module',
    plugins: ['jsx', 'typescript', 'classProperties', 'decorators-legacy'],
  });

  cb(ast, { traverse, t, generate });

  let modifiedCode = code; // 默认返回原 code

  // 查找包装后的对象表达式
  if (ast.program.body[0]?.type === 'ExpressionStatement' &&
    ast.program.body[0].expression?.type === 'ObjectExpression') {

    const objExpr = ast.program.body[0].expression;
    const searchListProp = objExpr.properties.find(
      p => t.isIdentifier(p.key) && p.key.name === 'searchList' && t.isArrayExpression(p.value)
    );

    if (searchListProp) {
      // --- 关键修改：生成整个 ObjectProperty 节点 ---
      const result = generate.default(searchListProp, { quotes: 'single' }, wrappedCode);
      // result.code 现在会是 'searchList: [...]'
      modifiedCode = result.code;
    }
  }

  return modifiedCode; // 返回完整的 'searchList: [...]' 字符串
}
function handleScript(f, currentSource) {
  // try {
  {
    const scriptContent = f.script.content;
    const scriptStart = f.script.start;
    const scriptEnd = f.script.end;

    const ast = parse(scriptContent, {
      sourceType: 'module',
      plugins: [
        'jsx',
        'classProperties',
        'objectRestSpread',
        'decorators-legacy',
        'typescript'
      ],
      ranges: true,
      errorRecovery: true
    });

    let modifications = [];
    let propertyToRemove = ['superQuery', 'superForm', 'basicQuery']; // 要删除的属性名
    let methodsToRemove = ['search', 'reset', 'superQuerySearch', 'sortChange', 'dateFun', 'btnsearch1', 'btnsearch2', 'btnsearch3', 'btnsearch4', 'superQuerySearchInbound']; // 要删除的方法名

    traverse.default(ast, {
      // 处理函数调用
      CallExpression(path) {
        const {node} = path;
        if (t.isMemberExpression(node.callee)) {
          const {object, property} = node.callee;

          // 处理initData调用
          if (t.isThisExpression(object) && t.isIdentifier(property) && property.name === 'initData' && node.arguments.length > 0) {
            const argsStart = node.arguments[0].start;
            const argsEnd = node.arguments[node.arguments.length - 1].end;

            echoLog(`script 删除initData调用参数`)
            modifications.push({
              start: scriptStart + argsStart,
              end: scriptStart + argsEnd,
              replacement: ''
            });
          }

        }
      },

      // 处理Property
      ObjectProperty(path) {
        // 处理superQueryJson
        if (t.isIdentifier(path.node.key) && path.node.key.name === 'superQueryJson') {
          if (path && t.isArrayExpression(path.node.value)) {
            const arrayElements = path.node.value.elements;
            const newElements = arrayElements.filter(element => {
              if (!t.isObjectExpression(element)) return true;

              const properties = element.properties;
              const item = {};
              properties.forEach(prop => {
                if (t.isIdentifier(prop.key)) {
                  const value = t.isStringLiteral(prop.value)
                    ? prop.value.value : t.isNumericLiteral(prop.value)
                      ? prop.value.value : t.isBooleanLiteral(prop.value)
                        ? prop.value.value : prop.value;
                  item[prop.key.name] = value;
                }
              });

              return !shouldRemoveItem(item);
            });

            if (newElements.length !== arrayElements.length) {
              const {start, end} = path.node.value;
              echoLog(`script.data 删除superQueryJson中无用的配置项`)
              modifications.push({
                start: scriptStart + start,
                end: scriptStart + end,
                replacement: generate.default(t.arrayExpression(newElements)).code
              });
            }
          }
        } else if (t.isIdentifier(path.node.key) && path.node.key.name === global.listQueryStr) {
          // if (path.node.value.properties.length) {
          //   echoLog(`script.data 设定fixedListQuery`)
          //   modifications.push({
          //     start: scriptStart + path.node.key.end,
          //     end: scriptStart + path.node.key.end,
          //     replacement: `: {},\r\n      fixedListQuery`
          //   })
          // }
        } else if (t.isIdentifier(path.node.key) && propertyToRemove.includes(path.node.key.name)) {
          // 删除多余property
          const commaLength = currentSource.slice(scriptStart + path.node.end, scriptStart + path.node.end + 1) === ',' ? 1 : 0
          echoLog(`script 删除多余property：${path.node.key.name}`)
          modifications.push({
            start: scriptStart + path.node.start,
            end: scriptStart + path.node.end + commaLength,
            replacement: ''
          });
        }
      },

      // 处理methods
      ObjectMethod(path) {
        // 改造initData方法
        if (t.isIdentifier(path.node.key) && path.node.key.name === 'data') {
          if (path.node.body.body[0].argument.properties.every(prop => prop.key.name !== 'superQueryJson')) {
            echoLog(`script.data 添加属性：superQueryJson`)
            modifications.push({
              start: scriptStart + path.node.body.body[0].argument.start + 1,
              end: scriptStart + path.node.body.body[0].argument.start + 1,
              replacement: `\r\n      superQueryJson: [],`
            });
          }
          if (path.node.body.body[0].argument.properties.every(prop => prop.key.name !== 'systemSearchView')) {

            const orderItemsPath = findFirstTargetPathFromAst(ast, 'orderItems')
            const orderItemsCode = (() => {
              if (orderItemsPath) {
                const commaLength = currentSource.slice(scriptStart + orderItemsPath.node.end, scriptStart + orderItemsPath.node.end + 1) === ',' ? 1 : 0
                echoLog(`script.data 删除原orderItems`)
                modifications.push({
                  start: scriptStart + orderItemsPath.node.start,
                  end: scriptStart + orderItemsPath.node.end + commaLength,
                  replacement: ``
                })
                const newOrderItems = currentSource.slice(scriptStart + orderItemsPath.node.start, scriptStart + orderItemsPath.node.end)
                if (newOrderItems.indexOf('_') === -1) delete mustHand.orderItems_sortProp
                return newOrderItems
              } else {
                return `orderItems: [] // 排序`
              }
            })()

            const conditionPath = findFirstTargetPathFromAst(ast, 'searchList')
            const conditionCode = (() => {
              if (conditionPath) {
                const commaLength = currentSource.slice(scriptStart + conditionPath.node.end, scriptStart + conditionPath.node.end + 1) === ',' ? 1 : 0
                echoLog(`script.data 删除原searchList`)
                modifications.push({
                  start: scriptStart + conditionPath.node.start,
                  end: scriptStart + conditionPath.node.end + commaLength,
                  replacement: ``
                })

                const transformedCodeString = codeAsAstHandler(
                  currentSource.slice(scriptStart + conditionPath.node.start, scriptStart + conditionPath.node.end),
                  (ast) => {
                    traverse.default(ast, {
                      ObjectProperty(path) {
                        const { node } = path;
                        // 1. 首先检查这个 ObjectProperty 的 key 是否是 'searchList'
                        if (t.isIdentifier(node.key) && node.key.name === 'searchList') {
                          // 2. 关键：检查它的父节点是否是我们期望的类型 (通常是 ObjectExpression)
                          // 这可以确保我们找到的是顶层或特定上下文下的 searchList 属性
                          if (t.isObjectExpression(path.parent)) {
                            // 3. 再检查它的 value 是否是 ArrayExpression
                            if (t.isArrayExpression(node.value)) {

                              // --- 在这里进行你的转换逻辑 ---
                              // 例如，转换 searchList 数组中的每个元素
                              const newElements = node.value.elements
                              .map(elementNode => {
                                if (t.isObjectExpression(elementNode)) {
                                  let fieldNode = null;
                                  let fieldValueNode = null;
                                  let symbolNode = null;

                                  elementNode.properties.forEach(prop => {
                                    if (t.isIdentifier(prop.key)) {
                                      if (prop.key.name === 'field') fieldNode = prop.value;
                                      else if (prop.key.name === 'fieldValue') fieldValueNode = prop.value;
                                      else if (prop.key.name === 'symbol') symbolNode = prop.value;
                                    }
                                  });
                                  if ([
                                    'productCode',
                                    'productsCode',
                                    'productName',
                                    'productsName',
                                    'productDrawingNo',
                                    'productsDrawingNo',
                                    'drawingNo',
                                    'model',
                                    'spec',
                                    'drawingSheetNo',
                                  ].includes(fieldNode.value)) return null
                                  if (fieldNode && symbolNode) {
                                    return t.objectExpression([
                                      t.objectProperty(t.identifier('prop'), fieldNode),
                                      t.objectProperty(t.identifier('symbol'), symbolNode),
                                      t.objectProperty(t.identifier('fixed'), t.booleanLiteral(true)),
                                      [undefined, ''].every(item => item !== fieldValueNode?.value) ? t.objectProperty(t.identifier('value'), fieldValueNode) : null
                                    ].filter(el => el !== null));
                                  }
                                }
                                return null;
                              })
                              .filter(el => el !== null);

                              // 替换原数组
                              node.value = t.arrayExpression(newElements);
                              path.stop(); // 停止遍历
                            }
                          }
                        }
                      }
                    });
                  }
                ).replace('searchList', 'condition')

                return transformedCodeString + (commaLength ? ',' : '')
              } else {
                return `condition: [ // 视图查询条件（自动根据绑定表格的列顺序排序）
            // 这里放置系统原顶栏显示的查询元素，如：
            // {
            //   prop: 'createTime', // 属性*
            //   value: [this.jnpf.getToday('YYYY-MM-DD HH:mm:ss', 'today-29'), this.jnpf.getToday('YYYY-MM-DD HH:mm:ss', 'todayLastMoment')], // 默认值
            //   symbol: 'between', // 比较符*
            //   timeOffset: true, // 保存视图后的静态时间区间随实际查询时刻偏移
            //   fixed: true // 是否在搜索栏显示
            // },
            // { prop: 'orderNo', symbol: 'like', fixed: true },
          ],`
              }
            })()
            const hasProductFlag = currentSource.includes('  <el-table-column prop="productCode"')

            echoLog(`script.data 中添加属性：systemSearchView`)
            delete mustHand.systemSearchView
            modifications.push({
              start: scriptStart + path.node.body.body[0].argument.start + 1,
              end: scriptStart + path.node.body.body[0].argument.start + 1,
              replacement: `\r\n      systemSearchView: [{
        matchLogic: "AND", // 条件逻辑（固定）*
        fullName: "默认视图", // 视图名称*
        conditionJson: { // 视图内容配置*
          ${conditionCode}
          ${hasProductFlag ? '' : '// '}keywordQuery: this.jnpf.getKeywordQuery('product'), // 带有产品信息的表使用此预设
          pageSize: 20, // 每页条数*
          ${orderItemsCode}
        },
      }],`
            });
            // console.log(modifications[modifications.length - 1].replacement);
          }
        } else if (t.isIdentifier(path.node.key) && (path.node.key.name === 'created' || path.node.key.name === 'mounted')) {
          const bodyLines = path.node.body.body
          for (let i = 0; i < bodyLines.length; i++) {
            if (t.isExpressionStatement(bodyLines[i])) {
              // created中第i行代码
              const lineCode = currentSource.slice(scriptStart + bodyLines[i].expression.start, scriptStart + bodyLines[i].expression.end);
              if (lineCode.startsWith(`this.${global.listQueryStr}`)) { // 给$$listQuery赋值的属性，改为赋值给fixedListQuery
                // echoLog(`script.created 修改第${i + 1}行代码：${currentSource.slice(bodyLines[i].expression.start + scriptStart, bodyLines[i].expression.end + scriptStart).replaceAll(`this.${global.listQueryStr}`, 'this.fixedListQuery')}`)
                // modifications.push({
                //   start: scriptStart + bodyLines[i].expression.start,
                //   end: scriptStart + bodyLines[i].expression.end,
                //   replacement: currentSource.slice(bodyLines[i].expression.start + scriptStart, bodyLines[i].expression.end + scriptStart).replaceAll(`this.${global.listQueryStr}`, 'this.fixedListQuery')
                // });
              } else if (['this.initData(', 'this.search(', 'this.getAdvancedQuery('].some(item => lineCode.includes(item))) { // 去除页面默认进行的初次表格数据获取请求
                echoLog(`script.created 去除第${i + 1}行代码：${currentSource.slice(scriptStart + bodyLines[i].expression.start, scriptStart + bodyLines[i].expression.end)}`)
                modifications.push({
                  start: scriptStart + bodyLines[i].expression.start,
                  end: scriptStart + bodyLines[i].expression.end,
                  replacement: ''
                });
              }

            }
          }
        } else if (t.isIdentifier(path.node.key) && path.node.key.name === 'initData' && !path.node.params.length) {
          if (path.node.params.length !== 1 || path.node.params[0].name !== global.listQueryStr) {
            echoLog(`script.methods 修改initData方法参数`)
            delete mustHand.methods_initData
            modifications.push({
              start: scriptStart + path.node.key.end,
              end: scriptStart + path.node.body.body[0].start,
              replacement: `(listQuery) {
      if (listQuery) this.${global.listQueryStr} = listQuery;
      if (!this.${global.listQueryStr}?.pageSize) return this.$message.error('请先等待视图加载完成！');
      const listLoadKey = this.listLoadKey = +new Date();
      if (listLoadKey !== this.listLoadKey) return; // 请求过期\r\n
      `
            })
          }
        } else if (t.isIdentifier(path.node.key) && methodsToRemove.includes(path.node.key.name)) {
          // 删除多余method
          const commaLength = currentSource.slice(scriptStart + path.node.end, scriptStart + path.node.end + 1) === ',' ? 1 : 0
          echoLog(`script.methods 删除多余方法：${path.node.key.name}`)
          // console.log(currentSource.slice(scriptStart + path.node.start, scriptStart + path.node.end + commaLength))
          modifications.push({
            start: scriptStart + path.node.start,
            end: scriptStart + path.node.end + commaLength,
            replacement: ''
          });
        }
      }
    });

    // 应用所有修改
    if (modifications.length > 0) {
      modifications.sort((a, b) => b.start - a.start);
      modifications = modifications.filter((item, index) => {
        // 检查当前 item 是否被 modifications 中的其他某一项完全包含
        const isContained = modifications.some((otherItem, otherIndex) => {
          if (index === otherIndex) return false;
          return otherItem.start <= item.start && item.end <= otherItem.end;
        });
        return !isContained;
      });
      let result = currentSource;
      for (const mod of modifications) {
        // console.log('=================\n', result.slice(mod.start, mod.end) , '\n--------------->\n', mod.replacement)
        result = result.slice(0, mod.start) + mod.replacement + result.slice(mod.end);
      }
      return result;
    }

    return currentSource;
  }
  // } catch (error) {
  //   console.error(` ❌ ${global.currentPath}：处理script部分出错`, error.message);
  //   return currentSource;
  // }
}

function eachAstElement(ast, fn) {
  if (!ast) return;
  if (ast.children === undefined) return;
  fn(ast);
  ast.children.forEach(item => {
    if (item.type !== 1) return;
    eachAstElement(item, fn);
  });
}

// 查找页面的关键变量名
function setVariable(f) {
  if (f.script.content.indexOf('initData(') < 0) throw new Error(` ❌ 未找到initData方法!`);
  const match_listQueryStr = f.script.content.match(/return\s*{.*?(initListQuery|listQuery|orderForm|linesQuery|tableQuery|inboundForm|productForm|processForm):\s*\{(?!\})/s);
  const match_JNPFTableRefStr = f.template.content.match(/<JNPF-table\s*.*?ref="(.*?)"/s);
  // global.sortPropList = [...f.script.content.matchAll(/prop\s*=*\s*['"]([^'"]+)['"]/g)].map(match => match[1])
  // global.sortPropList = []

  if (match_listQueryStr && match_listQueryStr) {
    global.JNPFTableRefStr = match_JNPFTableRefStr[1]
    global.listQueryStr = match_listQueryStr[1]
    if (match_listQueryStr[1].includes('init')) {
      throw new Error(` ❌ ${global.currentPath}：请勿使用 ${match_listQueryStr[1]} 作为列表查询请求体，请手动把代码中 ${match_listQueryStr[1]} 改为作为列表查询请求体！`)
    }
  } else {
    throw new Error(` ❌ ${global.currentPath}：未找到有效关键变量名，请检查是否在created或mounted中给关键变量做了完全的初始赋值`);
  }
}

function handleStr(str) {
  const f = compiler.parseComponent(str, {outputSourceRange: true});
  let result = str;

  setVariable(f)

  // 先处理script部分
  if (f.script) {
    result = handleScript(f, result);
  }

  // 然后处理template部分
  if (f.template) {
    result = handleTemplate(f, result);
  }

  return result;
}

function handleTemplate(f, currentSource) {
  const {ast, errors} = compiler.compile(f.template.content, {outputSourceRange: true});
  if (!ast) {
    console.log(` ❌ ${global.currentPath}：模板AST生成失败`);
    return currentSource;
  }

  const foundElement = [];
  eachAstElement(ast, item => {
    if (foundElement.length) return;
    const res = findFn(item);
    if (res) foundElement.push(res);
  });

  if (foundElement.length === 0) return currentSource;

  function handleTemplateStr(str) {
    const f = compiler.parseComponent(str, {outputSourceRange: true});
    let result = str;

    // 处理template部分
    if (f.template) {
      result = handleTemplate(f, result);
    }

    return result;
  }

  return handleTemplateStr(executeSource(foundElement[0], f, currentSource));
}

function executeSource(ast, f, currentSource) {
  const con = f.template.content;
  let modifiedTemplate = con;

  if (ast.attrsMap.sortable === 'custom') {
    echoLog(`template 删除<${ast.tag} ... />的 sortable="custom"`)
    modifiedTemplate =
      con.slice(0, ast.rawAttrsMap.sortable.start - 1) +
      con.slice(ast.rawAttrsMap.sortable.end, ast.end) +
      con.slice(ast.end + 1);
  }
  // else if (!ast.attrsMap.sortProp && ast.attrsMap.prop !== 'createByName' && global.sortPropList.some(item => item === ast.attrsMap.prop)) {
  //   echoLog(`template 给<${ast.tag} ... />指定 sortProp 为其本身 prop`)
  //   const lastAttr = Object.keys(ast.rawAttrsMap)[Object.keys(ast.rawAttrsMap).length - 1]
  //   global.sortPropList.splice(global.sortPropList.indexOf(ast.attrsMap.prop), 1, '!' + ast.attrsMap.prop)
  //   modifiedTemplate =
  //     con.slice(0, ast.rawAttrsMap[lastAttr].end) +
  //     ` sortProp="${ast.attrsMap.prop}"` +
  //     con.slice(ast.rawAttrsMap[lastAttr].end)
  // }
  else if (ast.events?.['sort-change']) {
    echoLog(`template 删除<${ast.tag} ... />的 @sort-change`)
    modifiedTemplate =
      con.slice(0, ast.events['sort-change'].start - 1) +
      con.slice(ast.events['sort-change'].end, ast.end) +
      con.slice(ast.end + 1);
  } else if (Object.keys(ast.rawAttrsMap).some(key => ast.tag !== 'JNPF-table' && ast.rawAttrsMap[key].value.includes('initData'))) {
    const targetAttrKey = Object.keys(ast.rawAttrsMap).find(
      item => ast.rawAttrsMap[item].value.includes('initData'));
    echoLog(`template 删除<${ast.tag} ... />的initData传参`)
    modifiedTemplate =
      con.slice(0, ast.rawAttrsMap[targetAttrKey].start - 1) +
      ` ${targetAttrKey}="initData()"` +
      con.slice(ast.rawAttrsMap[targetAttrKey].end, ast.end) +
      con.slice(ast.end + 1);
  } else if ((ast.tag === 'el-row' && ast.attrsMap.class?.indexOf('JNPF-common-search-box') !== -1) || ast.attrsMap.ref === 'fangan') {
    echoLog(`template 替换<${ast.tag} ... />为<JNPF-tableQuery ... />`)
    modifiedTemplate =
      con.slice(0, ast.start) +
      `<JNPF-tableQuery :listQuery="${global.listQueryStr}" :systemSearchView="systemSearchView" tableRef="${global.JNPFTableRefStr}" />` +
      con.slice(ast.end + 1);
    delete mustHand.jnpfTableQuery;
  } else if (ast.tag === 'JNPF-table' && !ast.attrsMap[':listQuery']) {
    echoLog(`template 给<${ast.tag} ... />添加自定义查询的依赖传参与事件`)
    if (!ast.attrsMap['v-if']) delete mustHand.tableVIf
    const lastAttr = Object.keys(ast.rawAttrsMap)[Object.keys(ast.rawAttrsMap).length - 1]
    modifiedTemplate =
      con.slice(0, ast.rawAttrsMap[lastAttr].end) +
      ` :listQuery="${global.listQueryStr}" @queryChange="initData" :queryJson="superQueryJson"` +
      con.slice(ast.rawAttrsMap[lastAttr].end)
  } else if (ast.tag === 'el-tooltip' && ast.attrsMap['content'] === '高级查询') {
    echoLog(`template 替换原高级查询入口为调整排序入口<${ast.tag} ... />`)
    modifiedTemplate = con.slice(0, ast.start)
      + `<el-tooltip effect="dark" content="数据排序设置" placement="top">
                <el-link icon="icon-ym icon-ym-generator-flow JNPF-common-head-icon" :underline="false"
                  @click="$refs.${global.JNPFTableRefStr}.showSortDrawer()" />
              </el-tooltip>`
      +
      con.slice(ast.end + 1);
    delete mustHand.showSortDrawer;
  } else if (ast.tag === 'SuperQuery') {
    echoLog(`template 删除原高级查询组件<${ast.tag} ... />`)
    modifiedTemplate =
      con.slice(0, ast.start) + con.slice(ast.end + 1);
  }

  return currentSource.slice(0, f.template.start) +
    modifiedTemplate +
    currentSource.slice(f.template.end);
}

// 原有的findFn保持不变
function findFn(element) {
  if (element.tag === 'JNPF-table' && element.events?.['sort-change']) {
    return element;
  }
  if (element.tag === 'JNPF-table' && !element.attrsMap[':listQuery']) {
    return element;
  }
  if (element.tag === 'el-table-column' && element.attrsMap.sortable === 'custom') {
    return element;
  }
  // if (element.tag === 'el-table-column' && element.attrsMap.prop !== 'createByName' && !element.attrsMap.sortProp && global.sortPropList.some(item => item === element.attrsMap.prop)) {
  //   return element;
  // }
  if (Object.keys(element.rawAttrsMap).some(key => {
    const valueStr = element.rawAttrsMap[key].value;
    return element.tag !== 'JNPF-table' && valueStr.includes('initData') && valueStr !== 'initData()';
  })) {
    return element;
  }
  if ((element.tag === 'el-row' && element.attrsMap.class?.indexOf('JNPF-common-search-box') !== -1) || element.attrsMap.ref === 'fangan') {
    return element;
  }
  if (element.tag === 'el-tooltip' && element.attrsMap.content === '高级查询') {
    return element;
  }
  if (element.tag === 'SuperQuery') {
    return element;
  }
  return null;
}

// 文件处理函数保持不变
async function eachFile(dPath, discardLocalChanges = false) {
  if (!fs.existsSync(dPath)) throw new Error('路径不存在');

  console.log(` 🚀 开始处理：${dPath}`)
  if (discardLocalChanges) {
    const cheoutFlag = await new Promise((resolve, reject) => {
      process.exec('git checkout -- ' + dPath, (error, stdout, stderr) => {
        if (error) {
          console.error('checkout failed', error);
          return reject()
        }
        resolve(true);
      });
    }).catch(err => false)
    if (!cheoutFlag) return
  }

  const stat = fs.statSync(dPath);
  if (stat.isFile()) return singleFileHandler(dPath);

  fs.readdirSync(dPath).forEach(file => {
    const curPath = path.join(dPath, file);
    if (fs.statSync(curPath).isFile()) {
      singleFileHandler(curPath);
    } else {
      eachFile(curPath);
    }
  });
}

function singleFileHandler(filePath) {
  if (!filePath.endsWith('.vue')) return;

  const str = fs.readFileSync(filePath, 'utf-8');
  global.currentPath = filePath;

  let result = handleStr(str);
  result = result
  .replaceAll(`this.search('basic')`, `this.initData()`)
  .replaceAll(`this.search('super')`, `this.initData()`)
  .replaceAll(`search('basic')`, `initData()`)
  .replaceAll(`search()`, `initData()`)
  .replaceAll(`reset()`, `initData()`)
  .replaceAll(`t1.create_time`, `createTime`)
  .replaceAll(`t.create_time`, `createTime`)
  .replaceAll(`create_time`, `createTime`)
  fs.writeFileSync(filePath, result, {
    encoding: 'utf-8',
    flag: 'w',
  });

  if (!echoIndex) return console.error(`\n❌ 本次执行未进行任何改动！`)

  console.log(`\n==============================✅_自动部分处理完成！请检查处理结果并继续完成手动处理部分。==============================`)
  // console.log(`💡_本次使用 ${global.listQueryStr} 作为数据请求体！`)


  if (Object.keys(mustHand).length) console.log(`以下必要内容未自动处理:\n❌  ${Object.values(mustHand).join('\n❌  ')}`)
  if (result.includes('search(')) console.log(`❌️ 有 search(...) 方法未被删除！`)
  if (result.includes('reset(')) console.log(`❌️ 有 reset(...) 方法未被删除！`)
  if (result.includes('searchList')) console.log(`❌️ 有 searchList 未被删除！`)
  if (result.includes('<el-tree ')) console.log(`❌️ 如果带有左侧树，刷新数据的列表刷新方法应改为 this.$refs.${global.JNPFTableRefStr}.queryChange(this.${global.listQueryStr})`)
  // console.log(`💡_本次为 ${global.sortPropList.filter(item => item.startsWith('!')).map(item => item.replace('!', '')).join('、')} 指定了sortProp！`)

  console.log(`\n✍️_ 处理后检查：`)
  console.log(`1、如果 ${global.listQueryStr} 中有生效的键名与某个 el-table-column 标签的 prop 相同，把此键转换到默认视图的 condition 中。顺便删除无效的字段`)
  // console.log(`2、根据methods中 sortChange 方法，给特定 el-table-column 标签指定 sortProp ；完成后删除 sortChange`)
  console.log(`2、是否已完全删除 页面默认进行的初次表格数据获取请求`)
  // console.log(`2、是否原 sortChange 中的排序转义都已使用 sortProp 指定完成`)
  // console.log(`3、是否存在 search reset 方法的调用，需要改为 initData`)
  // console.log(`4、是否还有给 searchList 的赋值，需要改为赋值给 condition`)
  console.log(`3、把 initData 内容中 listLoadKey 利用起来；`)
  console.log(`4、点开关键词配置弹窗，查看是否有需要使用select类型的列对应的label，需要把其放到 superQueryJson 中适配`)
  console.log(`5、是否原固定顶栏的查询条件，被转换到 condition`)
  // console.log(`6、如果是带有产品信息的表格，需要解除 keywordQuery 的禁用，并删除 condition 的产品相关字段`)
}

eachFile('D:\\Desktop\\os-web-dasunyun\\src\\views\\warehouseManagement\\finishedProductWarehouseManagement\\inventoryDetaisList\\index.vue')
